package com.melody.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.melody.entry.MusicInfo;
import com.melody.entry.Result;
import com.melody.entry.UserFavorite;
import com.melody.service.UserFavoriteService;
import com.melody.mapper.UserFavoriteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author zxz
* @description 针对表【user_favorite(我的喜欢)】的数据库操作Service实现
* @createDate 2025-05-09 10:31:18
*/
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite>
    implements UserFavoriteService{

    @Autowired
    private UserFavoriteMapper UserFavoriteMapper;


    /**
     * 批量删除用户喜欢的音乐
     * */
    @Override
    public List<UserFavorite> batchDeleteUserFavorite(List<Long> musicIds,Integer userId) {
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("music_id",musicIds)
                .eq("user_id",userId);

        List<UserFavorite> userFavoriteList = UserFavoriteMapper.selectList(queryWrapper);
        int deleteCount = UserFavoriteMapper.delete(queryWrapper);
        if (deleteCount > 0) {
            // 如果删除成功，返回删除的记录
            return userFavoriteList;
        } else {
            // 如果删除失败，返回空列表
            return null;
        }

    }

    /**
     * 添加用户喜欢的音乐
     * @param musicId
     * @param userId
     * @return  添加成功的音乐信息
     * */
    @Override
    public String addUserFavorite(Integer musicId, Integer userId){
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("music_id",musicId)
                .eq("user_id",userId);
        if (UserFavoriteMapper.selectOne(queryWrapper) != null){
            return "已添加";
        }
        else if (this.selectByUserIdAndMusicId( musicId,userId) != null){
            this.updateByUserIdAndMusicId(musicId,userId);
            return "添加成功";
        }else {
            UserFavorite userFavorite = new UserFavorite();
            userFavorite.setUserId(userId);
            userFavorite.setMusicId(musicId);
            userFavorite.setIsLike(0);
            if (UserFavoriteMapper.insert(userFavorite) > 0){
                return "添加成功";
            }else {
                return "添加失败";
            }
        }
    }

    @Override
    public UserFavorite selectByUserIdAndMusicId(Integer musicId, Integer userId) {
        return UserFavoriteMapper.selectByUserIdAndMusicId(musicId,userId);
    }

    @Override
    public Integer updateByUserIdAndMusicId(Integer musicId, Integer userId) {
         return UserFavoriteMapper.updateByUserIdAndMusicId(musicId,userId);
    }
}




